package com.xpj.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class CacheConfig {

    /**
     * 本地缓存配置（Caffeine）
     */
    @Bean
    public LoadingCache<String, Object> localCache() {
        return Caffeine.newBuilder()
                .expireAfterWrite(60, TimeUnit.SECONDS)  // 60秒过期
                .maximumSize(10_000)  // 最大缓存10000条记录
                .initialCapacity(100)
                .build(key -> null);  // 加载函数，实际由Redis填充
    }

    /**
     * 初始化延迟执行线程池 用于执行缓存延迟删除
     */
    @Bean
    public ScheduledExecutorService delayedExecutor() {
        return Executors.newScheduledThreadPool(5, new ThreadFactory() {
            private final AtomicInteger counter = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "delayed-cache-evict-" + counter.getAndIncrement());
            }
        });
    }


    /**
     * 缓存预热专用线程池
     */
    @Bean("preloadExecutor")
    public Executor preloadExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(0);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("cache-preload-");
        // 拒绝策略：让提交任务的线程执行任务，避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
